package com.dingshi.security;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.dingshi.security.adapter.DiaryAdapter;
import com.dingshi.security.api.ApiResult;
import com.dingshi.security.api.ApiReturnResultListener;
import com.dingshi.security.api.DiaryApi;
import com.dingshi.security.db.SettingLoader;
import com.dingshi.security.entity.Diary;
import com.dingshi.security.util.StringUtils;
import com.dingshi.security.util.Utils;
import com.dingshi.security.view.LoadDialog;

public class DiaryActivity extends BaseActivity implements OnClickListener {

	private static final int ID_LOADING = 2012;
	private static final String TAG = "DiaryActivity";
	private TextView user_text;
	private TextView time_text;
	private ListView listView;
	private EditText input_edit;
	private Button btn_save;
	private DiaryAdapter adapter;
	private Button btn_back;
	private TextView title_text;
	protected ArrayList<Diary> list;
	private TextView tips;
	private Button btn_refresh;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.diary);

		initTopBar();

		initComponents();
		updateUI();

		getNumberList(SettingLoader.getGuardNum(this), SettingLoader.getDepartNum(this));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ID_LOADING:
			LoadDialog dialog = new LoadDialog(this, "努力加载中。。。");
			return dialog;

		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	private void getNumberList(String guardNum, String deprNum) {

		DiaryApi api = new DiaryApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {

			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
				JSONObject jsonEntity = apiResult.getJsonEntity();
				Log.e("aa", jsonEntity.toString());
				if (jsonEntity != null) {
					// {"d":[{"__type":"DiaryReturn:r","c":"aaa","t":"01:59:05"}],"t":1}

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							break;
						case 1:// 数组
							JSONArray array = jsonEntity.getJSONArray("d");
							if (array != null) {
								list = new ArrayList<Diary>();
								Diary diary = null;
								for (int i = 0; i < array.length(); i++) {
									diary = new Diary();
									JSONObject opt = (JSONObject) array.opt(i);
									diary.setContent(opt.getString("c"));
									diary.setCreateTime(opt.getString("t"));
									list.add(diary);
								}
								Log.i("Diary", "size is " + list.size());
							}

							updateList();

							break;
						case -1:// 错误
							dismissDialog(ID_LOADING);
							updateList();
							break;

						default:
							dismissDialog(ID_LOADING);
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public <T> void onReturnFailResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
				updateList();
			}

			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(ID_LOADING);
			}
		});
		api.getDiaryList(1, this, guardNum, deprNum);

	}

	private void updateList() {
		if (list != null && list.size() > 0) {
			tips.setVisibility(View.GONE);
			listView.setVisibility(View.VISIBLE);
			Log.e("list", "diary count is " + list.size());
			adapter = new DiaryAdapter(DiaryActivity.this, list);
			listView.setAdapter(adapter);
		} else {
			tips.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
		}
	}

	private void addDiary(final String guardnum, final String deprNumber, String content) {
		DiaryApi api = new DiaryApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {

			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);

				JSONObject jsonEntity = apiResult.getJsonEntity();
				Log.e("aa", jsonEntity.toString());
				if (jsonEntity != null) {
					// {"d":{"__type":"OperatorReturn:r","r":"5"},"t":0}

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							JSONObject json = jsonEntity.getJSONObject("d");
							String result = json.getString("r");
							if (!StringUtils.isNullOrEmpty(result)
									&& 0 < Integer.parseInt(result)) {
								Utils.showToast(DiaryActivity.this, "添加成功");
							} else {
								Utils.showToast(DiaryActivity.this, "添加失败");
							}
							break;
						case 1:// 数组

							break;
						case -1:// 错误

							break;

						default:
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
				getNumberList(guardnum, deprNumber);
			}

			@Override
			public <T> void onReturnFailResult(int requestCode,
					ApiResult<T> apiResult) {
				Log.e("aa", apiResult.getFailMessage());
				dismissDialog(ID_LOADING);
			}

			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(ID_LOADING);
			}
		});
		api.addDiary(1, this, guardnum, deprNumber, content);

	}

	private void initTopBar() {
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_refresh = (Button) findViewById(R.id.btn_refresh);
		btn_refresh.setVisibility(View.VISIBLE);
		title_text = (TextView) findViewById(R.id.title_text);
		btn_back.setOnClickListener(this);
		title_text.setText("值班日记");

	}

	private void updateUI() {
		listView.setCacheColorHint(Color.TRANSPARENT);
		time_text.setText(Utils.convertTime(System.currentTimeMillis()));
	}

	private void initComponents() {
		user_text = (TextView) findViewById(R.id.username);
		time_text = (TextView) findViewById(R.id.timestamp);
		tips = (TextView) findViewById(R.id.tips);
		listView = (ListView) findViewById(R.id.listView1);
		input_edit = (EditText) findViewById(R.id.input_edit);
		btn_save = (Button) findViewById(R.id.btn_save);

		btn_save.setOnClickListener(this);
		btn_refresh.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_save:
			//
			String content = input_edit.getText().toString();
			if (StringUtils.isNullOrEmpty(content)) {
				Utils.showToast(this, "您还没有任何填写内容");
				return;
			}

			addDiary(SettingLoader.getGuardNum(this), SettingLoader.getDepartNum(this), content);

			input_edit.setText("");
			break;
		case R.id.btn_back:
			super.onBackPressed();
			break;
		case R.id.btn_refresh:
			getNumberList(SettingLoader.getGuardNum(this), SettingLoader.getDepartNum(this));
			break;

		default:
			break;
		}

	}

}
